// pages/Riders/RiderOrderDetail/RiderOrderDetail.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
var QQMapWX = require('../../../common/qqmap-wx-jssdk.min.js');
var qqmapsdk;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    longitude: 0,
    latitude: 0,
    order: {},
    MapContext: {}, // 地图实例
    polyline: [],
    markers: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.item){
      var item = JSON.parse(options.item);
      console.log(item)
      this.setData({
        order: item,
      })
    }
    this.MapContext = wx.createMapContext("maps", this);
    this.getUserAddress();
    qqmapsdk = new QQMapWX({
      key: 'MEZBZ-6D3O4-JPJU6-XRZRL-LH73V-PYFUZ'
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if(this.data.timeIntervalSeveral){
      clearTimeout(this.data.timeIntervalSeveral);
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 定位
  getUserAddress(e){
    var _this = this;
    wx.getSetting({
      success: (res) => {
        console.log(res,'res')
        if(res.authSetting['scope.userLocation']){
          _this._getLocation();
        }else{
          wx.authorize({
            scope: 'scope.userLocation',
            success: ()=>{
              console.log(e,'e')
              _this._getLocation();
            },
            fail: (err) => {
              console.log(err,'err')
              wx.showModal({
                title: '获取定位信息',
                content: '请允许获取您的位置信息，否则小程序部分功能将无法使用',
                success: (res) => {
                  if(res.confirm){
                    wx.openSetting({
                      success: (res) => {
                        if(res.authSetting['scope.userLocation']){
                          _this._getLocation();
                        }
                      },
                    })
                  }
                }
              })
            }
          })
        }
      }
    })
  },
  // 选择地图定位
  _getLocation(){
    console.log('定位')
    let _this = this;
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log(res,'位置信息')
        const latitude = res.latitude
        const longitude = res.longitude
        var markers = [];
        markers.push({
          id: 0,
          latitude: _this.data.order.receivingAddressInfo.latitude,
          longitude :_this.data.order.receivingAddressInfo.longitude,
          iconPath: `${assetsAddress}/riders/order/warehouseIcon.png`,
          width: 28,
          height: 34,
        })
        markers.push({
          id: 1,
          latitude: latitude,
          longitude :longitude,
          iconPath: `${assetsAddress}/riders/order/riderIcon.png`,
          width: 28,
          height: 34,
        })
        var polyline = [];
        // polyline.push({
        //   points: [{ longitude :longitude , latitude : latitude },{ longitude :_this.data.order.receivingAddressInfo.longitude , latitude : _this.data.order.receivingAddressInfo.latitude }],color: '#0091ff',width: 6,arrowLine: true,
        // })
        // polyline.push({
        //   points: [{ longitude :_this.data.order.receivingAddressInfo.longitude , latitude : _this.data.order.receivingAddressInfo.latitude }],color: '#0091ff',width: 6,arrowLine: true,
        // })
        _this. MapContext.moveToLocation( { longitude :longitude , latitude : latitude } )
        _this.setData({
          latitude: latitude,
          longitude: longitude,
          markers: markers,
          polyline: polyline,
        })
        _this.MapContext.addMarkers({
          // markers,
          // polyline,
          clear: true,
        })
        // TODO 上传骑手位置
        var riderUserId = wx.getStorageSync('riderUserId');
        updateRiderInfo({latitude: latitude,longitude: longitude,userId: riderUserId})
        .then(res => {
          if(res.success){

          }else{
            wx.showToast({
              title: res.errMessage,
              icon: 'none',
            })
          }
        })
        // 定时器
        if(_this.data.takeTotal > 0){
          var timeIntervalSeveral = setTimeout(_this._getLocation, 180000);
          _this.setData({
            timeIntervalSeveral,
            timeList,
          })
        }else{
          if(_this.data.timeIntervalSeveral){
            clearTimeout(_this.data.timeIntervalSeveral); //清除定时器
          }
        }
      },
      fail: (err) => {
        console.log(err,'err')
      }  
    })
  },
  // 导航
  getNavPath(){
    let _this = this;
    qqmapsdk.direction({
      mode: 'bicycling',//可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
      //from参数不填默认当前地址
      from: {
        latitude: _this.data.latitude,
        longitude: _this.data.longitude,
      },
      to: {
        latitude: _this.data.order.receivingAddressInfo.latitude,
        longitude: _this.data.order.receivingAddressInfo.longitude,
      }, 
      success: function (res) {
        console.log(res);
        var ret = res;
        var coors = ret.result.routes[0].polyline, pl = [];
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        var kr = 1000000;
        for (var i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
        }
        //将解压后的坐标放入点串数组pl中
        for (var i = 0; i < coors.length; i += 2) {
          pl.push({ latitude: coors[i], longitude: coors[i + 1] })
        }
        console.log(pl)
        //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
        _this.setData({
          // latitude:pl[0].latitude,
          // longitude:pl[0].longitude,
          polyline: [{
            points: pl,
            color: '#FF0000DD',
            width: 4
          }]
        })
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },
})